import os
from typing import Dict

module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir, 'count')  # full path to text.
fields = ['羽毛球1', '羽毛球2', '羽毛球3', '羽毛球4', '羽毛球5', '羽毛球6', '羽毛球7', '羽毛球8', '羽毛球9', '羽毛球10', '羽毛球11', '羽毛球12']
timelines = ['9:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00',
             '16:00-17:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00']


def read():
    with open(file_path, 'r', encoding='utf-8') as f:
        d = eval(f.read())
        return dict(d)


def write(d: Dict):
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(str(d))


def save(field, t):
    d = read()
    if fields[int(field) - 1] not in d.keys():
        d[fields[int(field) - 1]] = [timelines[int(t) - 1]]
    d[fields[int(field) - 1]].append(timelines[int(t) - 1])
    write(d)


def get_av_fields():
    d = read()
    av_fields = []
    for i in fields:
        if len(d.get(i, [])) == len(timelines):
            continue
        av_fields.append(i)
    return av_fields


def get_av_times(field_no: int):
    field = fields[field_no - 1]
    d = read()
    av_times = []
    for i in timelines:
        if i in d.get(field, []):
            continue
        av_times.append(i)
    return av_times


def save_cook(stu_id, cookies):
    file = os.path.join(module_dir, 'data', stu_id)
    with open(file, 'w', encoding='utf-8') as f:
        d = dict()
        d[stu_id] = cookies
        f.write(str(d))


def valid_field_time(s_field, s_time):
    d = read()
    if timelines[s_time - 1] in d.get(fields[s_field - 1], []):
        return False
    return True
